package com.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Random;

public class TokenUtil {

    private static final Random RANDOM = new SecureRandom();
    public static final String TOKEN_NAME = "token";

    public static String setSessionToken(HttpServletRequest request) {
        String token = generateGUID();
        setSessionToken(request, TOKEN_NAME, token);
        return token;
    }

    public static void setSessionToken(HttpServletRequest request, String tokenName, String token) {
        HttpSession session = request.getSession();
        try {
            session.setAttribute(tokenName, token);
        } catch (IllegalStateException var5) {
            throw new IllegalArgumentException(var5.getMessage());
        }
    }

    public static String getParamToken(HttpServletRequest request) {
        Map params = request.getParameterMap();
        Object token = params.get(TOKEN_NAME);
        if (null != token) {
            return ((String[]) token)[0];
        }
        return "";
    }

    public static boolean validToken(HttpServletRequest request) {
        String token = getParamToken(request);
        if (null == token || "".equals(token)) {
            return false;
        }
        HttpSession session = request.getSession();
        String tokenInSession = (String) session.getAttribute(TOKEN_NAME);
        if (!token.equals(tokenInSession)) {
            return false;
        }
        request.setAttribute(TOKEN_NAME, tokenInSession);
        session.removeAttribute(TOKEN_NAME);
        return true;
    }

    private static String generateGUID() {
        return (new BigInteger(165, RANDOM)).toString(36).toUpperCase();
    }

}